package com.pearl.jacksoncore.demo.databind.ser;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.type.*;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.*;

/**
 *
 * 
 * @author TD
 * @version 1.0
 * @date 2024/4/11
 */
public class ModifyPasswordBeanSerializerModifier extends BeanSerializerModifier {

    /**
     * 自定义和调整 BeanSerializer 序列化过程中使用的属性集合
     *
     * @param config         序列化配置
     * @param beanDesc       Bean 对象信息
     * @param beanProperties 属性集合
     * @return 属性集合
     */
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        System.out.println("changeProperties");
        // 查询是否开启某个特征
        boolean enabled = config.isEnabled(SerializationFeature.FAIL_ON_SELF_REFERENCES);

        // 获取当前Bean 的类型、真实 Class
        JavaType javaType = beanDesc.getType();
        Class<?> rawClass = javaType.getRawClass();

        // 循环所有属性集合
        for (BeanPropertyWriter beanPropertyWriter : beanProperties) {
            // 属性类型
            JavaType type = beanPropertyWriter.getType();
            // 属性名称
            String name = beanPropertyWriter.getName();
            // 属性的序列化器
            JsonSerializer<Object> serializer = beanPropertyWriter.getSerializer();
            // 属性的类型列化器
            TypeSerializer typeSerializer = beanPropertyWriter.getTypeSerializer();
            // 是否有Null值序列化器
            boolean hasNullSerializer = beanPropertyWriter.hasNullSerializer();
            // 获取注解
            Annotation annotation = beanPropertyWriter.getAnnotation(JsonSerialize.class);

            // 修改字段名称
            if("password".equals(name)){
                // 当前属性Writer对象，注册自定义的序列化器
                beanPropertyWriter.assignSerializer(new JsonSerializer<>() {
                    @Override
                    public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                        jg.writeString("********");
                    }
                });
            }
        }

        return beanProperties;
    }
}
